package com.simple.common.utils.ExcelUtil;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.BeanMap;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author susu
 * @Date 2024/2/19
 */
public class MapObjectUtil {

    /**
     * @description: 将object的list数据 转换成 map的list（如：List<Map<String, Object>>）
     * @param objDataList
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @author susu
     */
    public static List<Map<String, Object>> objListToMapList(List<?> objDataList){
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (objDataList==null || objDataList.size()<1){
            return null;
        }
        objDataList.forEach(obj->{
            try {
                Map<String, Object> map = MapObjectUtil.objectToMap(obj);
                dataList.add(map);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
        return dataList;
    }

    /**
     * @description: 将object数据转换成map数据
     * @param obj
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author susu
     */
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap();
        Class<?> cla = obj.getClass();
        Field[] fields = cla.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String keyName = field.getName();
            Object value = field.get(obj);
            if (value == null)
                value = "";
            map.put(keyName, value);
        }
        return map;
    }

    /**
     * @description: 使用 JSONObject 将object转换成map
     * @param obj
     * @return java.util.Map<?,?>
     * @author susu
     */
    public static Map<?, ?> objectToMap2(Object obj) {
        if (obj == null)
            return null;
        return JSONObject.parseObject(JSONObject.toJSONString(obj),Map.class);
    }

    /**
     * @description: 使用BeanMap将object转换成map
     * @param obj
     * @return java.util.Map<?,?>
     * @author susu
     */
    public static Map<?, ?> objectToMap3(Object obj) {
        if (obj == null)
            return null;
        return new BeanMap(obj);
    }




}

